package com.st.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.st.entity.Dept;
import com.st.service.IDeptService;

@RequestMapping("/dept/")
@Controller
public class DeptController {

	@Autowired
	private IDeptService deptService;
	/**
	 * 页面跳转
	 */
	@GetMapping("/list.do")
	public String deptList() {
		return "dept/list";
	}
	@GetMapping("/modify.do")
	public ModelAndView deptModify(Integer did,ModelAndView mv) {
		mv.addObject("did",did);
		mv.setViewName("dept/modify");
		return mv;
	}
	/**
	 * 获取部门列表
	 * 处理器返回json格式的字符串
	 * 1.导包 jackson
	 * 2.在Handler上加注解@ResponseBody
	 */
	@ResponseBody
	@RequestMapping("/getAll.json")
	public List getAll() {
		//1.获取参数
		//2.处理业务
		System.out.println("-----------");
		List depts = deptService.getAll();
		//3.返回结果
		return depts;
	}
	
	/**
	 * 根据关键字查询
	 */
	@ResponseBody
	@PostMapping("/search.json")
	public List searchJson(String key) {
		//1.获取参数
		//2.处理业务
		System.out.println("-----------");
		System.err.println(key);
		List depts = deptService.getByKey();
		System.out.println(depts);
		//3.返回结果
		return depts;
	}
	
	/**
	 * 获取单个部门信息
	 */
	@ResponseBody
	@PostMapping("/getOne.json")
	public Dept getOne(Integer did) {
		Dept dept = deptService.getByDid(did);
		return dept;
	}
	
	/**
	 * 修改部门
	 */
	@PostMapping("/modify.do")
	public ModelAndView modify(Dept dept,ModelAndView mv) {
		int res = deptService.modify(dept);
		if(res > 0) {
			//成功
			mv.setViewName("redirect:list.do");
		}else if(res == -2){
			mv.addObject("error", "重复的部门名");
			mv.setViewName("dept/modify");
		}else {
			//失败
			mv.addObject("error", "修改失败");
			mv.setViewName("dept/modify");
		}
		return mv;
	}
}
